package kr.hkit.androidcomplete03.ch28_1;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch28_1.common.Item;
import kr.hkit.androidcomplete03.ch28_1.common.MyAdapter;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class SaxParser extends Activity {
	ListView lists;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		lists = (ListView) findViewById(R.id.orderListView);
		new ParsingXml().execute("order.xml");
	}
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>>{
		ProgressDialog progressDlg;
		
		@Override
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(SaxParser.this, "Wait", "order.xml Parsing...");
		}
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str;
			SaxHandler handler = null;
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while( (str=br.readLine()) != null){
					sb.append(str);
				}
				
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser parser = factory.newSAXParser();
				XMLReader reader = parser.getXMLReader();
				
				handler = new SaxHandler();
				reader.setContentHandler(handler);
				
				InputStream is  = new ByteArrayInputStream(sb.toString().getBytes("utf-8"));
				reader.parse(new InputSource(is));
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} finally {
				try {br.close();} catch (IOException e) {}
			}
			return handler.arLists;
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(SaxParser.this, result);
			lists.setAdapter(adapter);
			progressDlg.dismiss();
		}
	}
	
	private class SaxHandler extends DefaultHandler {
		private static final String TAG = "SAX_HANDLER";
		boolean initItem;
		Item item;
		ArrayList<Item> arLists = new ArrayList<>();
		
		@Override
		public void startDocument() throws SAXException {
			Log.d(TAG, "startDocument()");
		}
		@Override
		public void endDocument() throws SAXException {
			Log.d(TAG, "endDocument()");
		}
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			Log.d(TAG, "startElement()");
			if (localName.equalsIgnoreCase("item")){
				//새로운 elemement가 시작이라면
				initItem = true;
				item = new Item();
			}
			if (attributes.getLength()>0){//해당 Element에 속성이 정의되어 있다면
				for(int i=0; i<attributes.getLength(); i++){
					if (attributes.getLocalName(i).equalsIgnoreCase("price")){
						item.setItemPrice(Integer.parseInt(attributes.getValue(i)));
					}else{
						item.setItemMaker(attributes.getValue(i));
					}
				}
			}
		}
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			Log.d(TAG, "endElement()");
		}
		@Override
		//<item maker="samsung" price="21000">여기에 왔을때 이벤트</item>
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			Log.d(TAG, "characters()");
			if (initItem){
				item.setItemName(new String(ch, start, length));
				arLists.add(item);
				initItem = false;
			}
		}
		
		
	}
}
